// TypeScript file
class soundPlay extends egret.Sprite{

    private sd:egret.Sound =null;
    private sdCh:egret.SoundChannel;
    private isPlay:Boolean = false;//是否在播放

    public constructor(){
        super();
        this.sd = new egret.Sound();
    }

    public startSound(soundName:string){
        this.soundStop();       
        
        this.sd = RES.getRes(soundName+"_mp3");
        if(!this.sd) return;
        this.sdCh = this.sd.play(0,1);
        //静音
        if(StageData.soundClose){
            if (soundName === 'bgmusic') {
                this.sdCh.volume = .5;
            } else {
                this.sdCh.volume = 1;
            }
        }else{
            this.sdCh.volume = 0;
        }
        this.isPlay = true;
        this.sdCh.addEventListener(egret.Event.SOUND_COMPLETE, this.soundPlayComplete,this);
    }

    private soundPlayComplete(e:egret.Event){
        //console.log("soundPlay ** End");
        this.sdCh.removeEventListener(egret.Event.SOUND_COMPLETE, this.soundPlayComplete,this);
        this.isPlay = false;
        this.dispatchEventWith("end");
    }

    public soundStop(){
        if(this.isPlay){
            this.sdCh.stop();
            this.sd = null;
            this.isPlay = false;
            this.sdCh.removeEventListener(egret.Event.SOUND_COMPLETE, this.soundPlayComplete,this);
        }
    }
    //单独播放
    public soundSinglePlay(soundName:string,soundComplete:Function=null){
        var sd:egret.Sound = RES.getRes(soundName+"_mp3");
        if(!sd) return;
        var sdCh:egret.SoundChannel = sd.play(0,1);
        //静音
        if(StageData.soundClose){
            if (soundName === 'bgmusic' || soundName === 'outCard') {
                sdCh.volume = .5;
            } else {
                sdCh.volume = 1;
            }
        }else{
            sdCh.volume = 0;
        }           
        var returnFun:Function = soundComplete;
        if(soundComplete){
            sdCh.addEventListener(egret.Event.SOUND_COMPLETE,(e) =>{
                returnFun();
            },this);
        }
    }
}